package sy4_Creational_Pattern.factory.method;

import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class XMLUtil {   
    public static Object getBean() {  //无参，要求配置文件里只配置一个类
        try {
            DocumentBuilderFactory dFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = dFactory.newDocumentBuilder();
            
            Document doc = builder.parse(new File("src/main/java/sy4_Creational_Pattern/factory/method/config.xml"));
            NodeList nl = doc.getElementsByTagName("className");  //根据标签名获取结点列表
           
            Node classNode=nl.item(0);  //文本结点
            String cName = classNode.getTextContent();  //获取文本结点的文本内容
            /*Node classNode = nl.item(0).getFirstChild();  //获取第一个结点
            String cName = classNode.getNodeValue(); */ //获取结点值（即类名）
            
            Class<?> clazz = Class.forName(cName);  //获取类类型对象
            return clazz.newInstance();  //创建类的实例
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}